package flc.ast.fragment;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.adapter.SelAudioAdapter;
import flc.ast.databinding.FragmentAudioBinding;
import flc.ast.dialog.AudioEditDialog;
import flc.ast.dialog.EditDialog;
import flc.ast.dialog.InfoDialog;
import flc.ast.dialog.RenameDialog;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.media.MediaLoader;
import stark.common.basic.media.audio.AudioPlayerImpl;
import stark.common.basic.media.audio.IAudioPlayer;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.TimeUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AudioFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AudioFragment extends BaseNoModelFragment<FragmentAudioBinding> implements IAudioPlayer.IListener {

    private SelAudioAdapter selAudioAdapter;
    protected IAudioPlayer mAudioPlayer;
    private List<AudioBean> listShow = new ArrayList<>();
    private int selPosition = 0;
    private ObjectAnimator mRotaAnimator;


    @Override
    protected int onCreate() {
        return R.layout.fragment_audio;
    }

    @Override
    protected void initView() {

        mAudioPlayer = new AudioPlayerImpl();
        mAudioPlayer.setListener(this);

        mDataBinding.rvAudioList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        selAudioAdapter = new SelAudioAdapter();
        mDataBinding.rvAudioList.setAdapter(selAudioAdapter);
        selAudioAdapter.addChildClickViewIds(R.id.ivSelAudioItemEdit);
        selAudioAdapter.setOnItemClickListener(this);
        selAudioAdapter.setOnItemChildClickListener(this);

        mDataBinding.ivPlayLast.setOnClickListener(this);
        mDataBinding.ivPlayNext.setOnClickListener(this);
        mDataBinding.ivPlay.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayLast://上一个
                if (selPosition > 0) {
                    selPosition--;
                    setPlayData();
                    mAudioPlayer.play(selAudioAdapter.getItem(selPosition).getPath());
                } else {
                    ToastUtils.showShort(getString(R.string.last_audio_tip));
                }
                break;
            case R.id.ivPlayNext://下一个
                if (selPosition >= listShow.size() - 1) {
                    ToastUtils.showShort(getString(R.string.next_audio_tip));
                } else {
                    selPosition++;
                    setPlayData();
                    mAudioPlayer.play(selAudioAdapter.getItem(selPosition).getPath());
                }
                break;
            case R.id.ivPlay://播放
                if (mAudioPlayer.isPlaying()) {
                    mAudioPlayer.pause();
                } else {
                    mAudioPlayer.resume();
                }
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        selAudioAdapter.getItem(selPosition).setSelected(false);
        selAudioAdapter.notifyItemChanged(selPosition);
        selPosition = position;
        selAudioAdapter.getItem(position).setSelected(true);
        selAudioAdapter.notifyItemChanged(position);
        mAudioPlayer.play(selAudioAdapter.getItem(position).getPath());
        setPlayData();
        mDataBinding.llPlay.setVisibility(View.VISIBLE);
        mRotaAnimator.start();
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivSelAudioItemEdit://编辑
                showEditDialog(position);
                break;
        }
    }

    @Override
    protected void initData() {
        initAnimator();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAudioPlayer != null) {
            mAudioPlayer.resume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (mAudioPlayer != null) {
            mAudioPlayer.pause();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mAudioPlayer != null) {
            mAudioPlayer.stop();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getPermission();
        } else {
            if (mAudioPlayer != null) {
                mAudioPlayer.stop();
                mDataBinding.llPlay.setVisibility(View.GONE);
            }
        }
    }

    private void setPlayData() {
        mDataBinding.tvPlayName.setText(selAudioAdapter.getItem(selPosition).getName());
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.reqManageExternalStoragePermission()
                .reqPermissionDesc(getString(R.string.get_music_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        ToastUtils.showShort(R.string.no_permission);
                    }
                }).request();
    }

    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<AudioBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<AudioBean>> emitter) {
                List<AudioBean> audioBeans = MediaLoader.loadAudio();
                emitter.onNext(audioBeans);
            }

            @Override
            public void accept(List<AudioBean> audioBeanList) {
                if (audioBeanList != null) {
                    listShow.addAll(audioBeanList);
                    selAudioAdapter.setList(audioBeanList);
                    mDataBinding.rvAudioList.setVisibility(View.VISIBLE);
                    mDataBinding.tvAudioNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvAudioList.setVisibility(View.GONE);
                    mDataBinding.tvAudioNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    private void initAnimator() {
        mRotaAnimator = ObjectAnimator.ofFloat(mDataBinding.ivPlayIcon, "rotation", 0f, 360f);
        mRotaAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mRotaAnimator.setInterpolator(new LinearInterpolator());//插值器实现匀速旋转
        mRotaAnimator.setDuration(3000);//时间
    }

    @Override
    public void onUpdatePlayTime(int curPlayTime, int duration) {
        mDataBinding.tvPlayTime.setText(TimeUtil.getMmss(curPlayTime) + "/" + TimeUtil.getMmss(duration));
        if (curPlayTime == duration) {
            mDataBinding.llPlay.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPlayChange(boolean isPlaying) {
        if (isPlaying) {
            mDataBinding.ivPlay.setImageResource(R.drawable.azantin);
            mRotaAnimator.start();
        } else {
            mDataBinding.ivPlay.setImageResource(R.drawable.abof);
            mRotaAnimator.cancel();
        }
    }

    private void showEditDialog(int position) {
        AudioEditDialog dialog = new AudioEditDialog(mContext);
        dialog.audioPath = listShow.get(position).getPath();
        dialog.setListener(new AudioEditDialog.Ilistener() {
            @Override
            public void clickRename() {
                showRenameDialog(position);
            }

            @Override
            public void clickShare() {
                IntentUtil.shareVideo(mContext, listShow.get(position).getPath());
            }

            @Override
            public void clickAddPrivacyFolder() {
                String filePath = FileUtil.generateFilePath(Content.myPrivacyFile, "." + FileUtils.getFileExtension(listShow.get(position).getPath()));
                FileUtils.copy(listShow.get(position).getPath(), filePath);
                ToastUtils.showShort(getString(R.string.add_suc));
            }

            @Override
            public void clickInfo() {
                showInfoDialog(position);
            }

            @Override
            public void clickDelete() {
                delete(position);
            }
        });
        dialog.show();
    }

    private void showRenameDialog(int position) {
        RenameDialog dialog = new RenameDialog(mContext);
        dialog.title = getString(R.string.file_rename);
        dialog.hint = getString(R.string.please_input_folder_name_text);
        dialog.setListener(new RenameDialog.Ilistener() {
            @Override
            public void clickRename(String name) {
                FileUtils.rename(listShow.get(position).getPath(), name + "." + FileUtils.getFileExtension(listShow.get(position).getPath()));
                getData();
            }
        });
        dialog.show();
    }

    private void delete(int position) {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        //从此文件夹删除
                        mContext.getContentResolver().delete(Uri.parse(listShow.get(position).getUri()), null, null);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String path) {
                        getData();
                        dismissDialog();
                        ToastUtils.showShort(getString(R.string.delete_suc));
                    }
                });
            }
        }, 1000);
    }

    private void showInfoDialog(int position) {
        InfoDialog dialog = new InfoDialog(mContext);
        dialog.videoPath = listShow.get(position).getPath();
        dialog.show();
    }

}